package com.example.demo.testLearning.threadPool;

import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;

import javax.annotation.Resource;
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @Author CHAS
 * 2024/8/27 22:50
 **/

public class ThreadPoolTest {
    public static void main(String[] args) throws InterruptedException, ExecutionException {
        // 创建线程池
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(2, 4, 10,
                java.util.concurrent.TimeUnit.SECONDS, new java.util.concurrent.ArrayBlockingQueue<Runnable>(2));
        RejectedExecutionHandler rejectedExecutionHandler = new ThreadPoolExecutor.AbortPolicy();
        threadPoolExecutor.shutdown();
        // 向线程池提交任务
//        threadPoolExecutor.submit(()->{});
//        threadPoolExecutor.execute(() -> {});
        ExecutorService executor = Executors.newSingleThreadExecutor();
        executor = Executors.newFixedThreadPool(2);
        executor = Executors.newScheduledThreadPool(5);
        executor = Executors.newSingleThreadExecutor();
        ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(2);
        ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>();
        map.put("key1", 1);
        Integer value = map.get("key1");
        map.computeIfAbsent("key2", k -> 2);

        CyclicBarrier barrier = new CyclicBarrier(5, () -> {
            System.out.println("所有线程都到达了屏障点");
        });
        Runnable task = () -> {
            try {
                // 执行任务
                barrier.await(); // 等待其他线程
            } catch (Exception e) {
                e.printStackTrace();
            }
        };
        new Thread(task).start();
        new Thread(task).start();
        System.out.println("主线程执行完毕");
        new Thread(task).start();

        new Thread(task).start();
        new Thread(task).start();
        System.out.println("主线程执行完毕");
        new Thread(task).start();

        CountDownLatch latch = new CountDownLatch(3);
        Runnable task1 = () -> {
            try {
                // 执行任务
            } finally {
                latch.countDown(); // 任务完成，计数器减一
            }
        };
        new Thread(task1).start();
        new Thread(task1).start();
        new Thread(task1).start();
        latch.await(); // 等待所有任务完成
        System.out.println("所有任务都完成了");

        CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
            if (true) {
                throw new RuntimeException("Exception");
            }
            return "Hello";
        }).exceptionally(ex -> "面试鸭");


        CompletableFuture<String> future1 = CompletableFuture.supplyAsync(() -> {
            if (true) {
                throw new RuntimeException("Exception");
            }
            return "Hello";
        }).handle((result, ex) -> {
            if (ex != null) {
                return "Default Value";
            }
            return result;
        });
        System.out.println(future.get());
        System.out.println(future1.get());

        AtomicIntegerArray array = new AtomicIntegerArray(10);
        array.set(0, 10);
        AtomicBoolean flag = new AtomicBoolean(false);

        AtomicInteger count = new AtomicInteger(0);
        AtomicReference reference = new AtomicReference<>();
        reference.set(new Object());
        AtomicReferenceArray<Object> referenceArray = new AtomicReferenceArray<>(10);
        referenceArray.set(0, new Object());
        System.out.println(array.get(0));
        DoubleAdder doubleAdder = new DoubleAdder();
        doubleAdder.add(1.0);
        double v = doubleAdder.doubleValue();
    }
}
class YesTest {
    private Object lockObject;
    public YesTest(Object lockObject){this.lockObject = lockObject;}
        public void lockObject(){
        synchronized(lockObject) {//作用于lock0bject这个对象
                System.out.println("修饰代码块");
            }
        }
            public synchronized void lockInstance() { //作用于YesTest这个实例
                System.out.println("修饰实例方法");
            }
                public static synchronized void lockstatic() { //作用于YesTest.class这个类对象
                System.out.println("修饰静态方法");

            }

    public static void main(String[] args) {
        YesTest yesTest = new YesTest(new Object());
    }
}

class SpinLock {
    // 使用AtomicBoolean来表示锁的状态，初始值为false，表示锁未被占用
    private AtomicBoolean locked = new AtomicBoolean(false);

    public void lock() {
        // 线程进入自旋状态，不断检查锁是否被释放
        while (!locked.compareAndSet(false, true)) {
            // 这里可以添加一些线程让步（Thread.yield）操作，以避免过度占用CPU资源
            // Thread.yield();
        }
    }

    public void unlock() {
        // 释放锁，将锁的状态设置为false
        locked.set(false);
    }
}

class SpinLockExample {
    public static void main(String[] args) {
        final SpinLock spinLock = new SpinLock();
        // 创建两个线程来模拟对共享资源的竞争
        Thread thread1 = new Thread(() -> {
            spinLock.lock();
            try {
                System.out.println("线程1获取到锁");
                // 模拟线程执行一些操作
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                spinLock.unlock();
                System.out.println("线程1释放锁");
            }
        });
        Thread thread2 = new Thread(() -> {
            spinLock.lock();
            try {
                System.out.println("线程2获取到锁");
                // 模拟线程执行一些操作
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                spinLock.unlock();
                System.out.println("线程2释放锁");
            }
        });
        thread1.start();
        // 稍微延迟一下启动线程2，以增加线程1先获取锁的概率
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        thread2.start();
        ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
    }
}
 class ThreadLocalExample {
    // 定义一个 ThreadLocal，用来保存每个线程独立的变量副本
    private static final ThreadLocal<String> threadLocalCounter = ThreadLocal.withInitial(() -> "0");

    public static void main(String[] args) {
        // 创建三个线程，每个线程都会有自己独立的变量副本
        Thread t1 = new Thread(() -> {
            incrementAndPrint();
        });

        Thread t2 = new Thread(() -> {
            incrementAndPrint();
        });

        Thread t3 = new Thread(() -> {
            incrementAndPrint();
        });

        // 启动线程
        t1.start();
        t2.start();
        t3.start();
    }

    private static void incrementAndPrint() {
        for (int i = 0; i < 5; i++) {
            int currentValue = i;
            threadLocalCounter.set(currentValue + 1+"t");
            System.out.println(Thread.currentThread().getName() + " : " + threadLocalCounter.get());
        }
    }
}
class InheritableThreadLocalExample {

    // 创建一个 InheritableThreadLocal 用来存储上下文信息
    private static final InheritableThreadLocal<String> context = new InheritableThreadLocal<>();

    public static void main(String[] args) throws InterruptedException {
        // 设置父线程中的变量
        context.set("Parent Thread Data");

        // 创建子线程
        Thread childThread = new Thread(() -> {
            System.out.println("Child Thread Initial Value: " + context.get());

            // 子线程中修改值
            context.set("Child Thread Data");
            System.out.println("Child Thread Modified Value: " + context.get());
        });

        // 启动子线程
        childThread.start();
        childThread.join();
        // 主线程输出
        System.out.println("Parent Thread Value: " + context.get());

        ReentrantLock lock = new ReentrantLock();
        lock.tryLock(1, TimeUnit.SECONDS);
//        RedissonClient redisson = null;
//        RLock lock1 = redisson.getLock("test");


            for (int i = 0; i < 1000; i++) {
                new Thread(() -> count++).start();
            }
            System.out.println(count); // 结果可能不为 1000
    }
    static volatile int count = 0;

}

 class CompletionServiceExample {
    public static void main(String[] args) {
        ExecutorService executor = Executors.newFixedThreadPool(2);
        CompletionService<Boolean> completionService = new ExecutorCompletionService<>(executor);

        completionService.submit(() -> {
            Thread.sleep(1000);
            System.out.println("子线程1执行完成");
            return true;
        });

        completionService.submit(() -> {
            Thread.sleep(500);
            System.out.println("子线程2执行完成");
            return true;
        });

        try {
            for (int i = 0; i < 2; i++) {
                Future<Boolean> result = completionService.take();
                System.out.println("任务执行成功：" + result.get());
            }
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        } finally {
            executor.shutdown();
        }
    }
}

class test{
    public static void main(String[] args) {

    }
}
